<?php
/**
 * Users
 * 
 * @package yarland.ru
 * @author Igor.Barkowsky@gmail.com
 * @copyright 2009
 * @version $Id$
 * @access public
 */
class UsersWizard extends Wizard
{
	/** users table name
	 * @var string
	 */
	var $table = "users";
	/** additionals tables prefix
	 * @var string
	 */
	var $pfx = "users_";
	/** users tables user ID field
	 * @var string
	 */
	var $pid = "user_id";
	var $table_accesses;
	var $table_adresses;
	var $table_blogs;
	var $table_clubs;
	var $table_contacts;
	var $table_events;
	var $table_friends;
	var $table_groups;
	var $table_groups_accesses;
	var $table_guests;
	var $table_info;
	var $table_interests;
	var $table_karma;
	var $table_messages;
	var $table_photoes;
	var $table_photoalbums;
	var $table_ratings;
	var $table_subscribers;
	var $table_tags;
	/**
	 * UsersWizard::__construct()
	 * 
	 * @param MyDB $db
	 * @param string $tablename
	 * @param string $pfx
	 * @param string $pid
	 * @return void
	 */
	function __construct(MyDB $db,$tablename = '',$pfx = '',$pid = '')
	{
		$this->db = $db;
		if(strlen($tablename) > 0){$this->table = mysql_real_escape_string($tablename);}
		if(strlen($pfx) > 0){$this->pfx = mysql_real_escape_string($pfx);}
		if(strlen($pid) > 0){$this->pid = $pid;}
		$this->table_accesses = $this->pfx."access";
		$this->table_adresses = $this->pfx."address";
		$this->table_blogs = $this->pfx."blogs";
		$this->table_clubs = $this->pfx."clubs";
		$this->table_contacts = $this->pfx."contacts";
		$this->table_events = $this->pfx."events";
		$this->table_friends = $this->pfx."friends";
		$this->table_groups = $this->pfx."groups";
		$this->table_groups_accesses = $this->pfx."group_access";
		$this->table_guests = $this->pfx."guests";
		$this->table_info = $this->pfx."info";
		$this->table_interests = $this->pfx."interests";
		$this->table_karma = $this->pfx."karma";
		$this->table_messages = $this->pfx."msgs";
		$this->table_photoes = $this->pfx."photos";
		$this->table_photoalbums = $this->pfx."photo_albums";
		$this->table_ratings = $this->pfx."rating";
		$this->table_subscribers = $this->pfx."subscribers";
		$this->table_tags = $this->pfx."tags";
	}
	/**
	 * Users::get_client_ip()
	 * 
	 * @return string
	 */
	function get_client_ip()
	{
		$ip = '';
	    $ip="неопределен";
		if(getenv("HTTP_CLIENT_IP"))
		{
			$ip = getenv("HTTP_CLIENT_IP");
		}
		elseif(getenv("HTTP_X_FORWARDED_FOR"))
		{
			$ip = getenv("HTTP_X_FORWARDED_FOR");
		}
		elseif(getenv("REMOTE_ADDR"))
		{
			$ip = getenv("REMOTE_ADDR");
		}
		return $ip;
	}
	/**
	 * Users::verify_admin_access()
	 * 
	 * @param mixed $login
	 * @param mixed $password
	 * @param integer $pass_in_md5
	 * @param string $ret
	 * @return
	 */
	function verify_admin_access ($login, $password, $pass_in_md5 = 0, $ret = '/control/')
	{
	    // группы администраторов
	    $groups = array("admin", "superadmin");
	
		if ($pass_in_md5 == 0)
		{
			$password = md5($password);
		}
	
		// Проверка существования метки login_a и логина пользователя login
		// наличие login_a говорит о том что пользователь уже авторизоавлся.
		if (isset($_SESSION['login_a']) && isset($_SESSION['login']))
		{
			// Если полученный login не совпадает с зарегистрированным в сессии, "убиваем" данные в сессии
			if ($login != $_SESSION['login'])
			{
				unset($_SESSION['user_id']);
				unset($_SESSION['login']);
				unset($_SESSION['login_a']);
				unset($_SESSION['password']);
			}
			// Если совпадают, проверяем наличие доступа у пользвателя
			else
			{
				$query = "SELECT u.id FROM $this->table as u, $this->table_groups as ug WHERE
					login='".mysql_real_escape_string($login)."' AND
					password = '".$_SESSION['password']."' AND
					ug.group IN  ('".implode("','", $groups)."')
					AND u.group = ug.id LIMIT 1";
	
				$sql = $this->db->query($query);
				// Если доступ разрешен, возвращаем true
				if ($this->db->nums($sql) > 0)
				{
					$row = $this->db->fetch($sql);
					$user_id = $row[0];
	                $ar = array();
					$ar['last_ip'] = $this->get_client_ip();
					$ar['last_visited_page'] = $_SERVER['HTTP_HOST'].(isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : "");
					$ar['last_visit'] = time();
					$this->db->update($this->table_info, $ar, " WHERE $this->pid = '$user_id' ");
					return true;
				}
				// Иначе возвращаем уничтожаем данные
				else
				{
					unset($_SESSION['user_id']);
					unset($_SESSION['login']);
					unset($_SESSION['login_a']);
					unset($_SESSION['password']);
					return false;
				}
			}
		}
	
		// Если нет метки login_a или нет данных в сессии, проверяем данные
	
		$query = "SELECT u.id FROM $this->table as u, $this->table_groups as ug WHERE
					login='".mysql_real_escape_string($login)."' AND
					password = '".$password."' AND
					ug.group IN  ('".implode("','", $groups)."')
					AND u.group = ug.id LIMIT 1";
	
		$sql = $this->db->query($query);
		if ($this->db->nums($sql) > 0)
		{
			$row = $this->db->fetch($sql);
			$user_id = $row[0];
			$_SESSION['login'] 		= $login;
			$_SESSION['password'] 	= $password;
			$_SESSION['user_id'] 	= $user_id;
			$_SESSION['login_a'] 	= md5(time());
	        $ar = array();
			$ar['last_ip'] = $this->get_client_ip();
			$ar['last_visited_page'] = $_SERVER['HTTP_HOST'].(isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : "");
			$ar['last_visit'] = time();
			$this->db->update($this->table_info, $ar, " WHERE $this->pid = '$user_id' ");
	
			return true;
		}
		else
		{
			return false;
		}
	}
	/**
	 * Users::admin_authorization()
	 * 
	 * @param string $ret
	 * @return
	 */
	function admin_authorization ($ret = '/control/')
	{
		if (isset($_POST['auth_submit']))
		{
			$login_result = $this->verify_admin_access($_POST['login'], $_POST['password'], 0, $ret);
			if ($login_result === false)
			{
				$_SESSION['system_message']['error'] = 'В доступе отказано. Проверьте правильность введенных данных.';
			}
			else
			{
				header("Location: ".$ret);
			}
		}
		elseif (isset($_SESSION['login_a']) && isset($_SESSION['login']))
		{
			$login_result = $this->verify_admin_access($_SESSION['login'], $_SESSION['password'], 1, $ret);
			if ($login_result === false)
			{
				$_SESSION['system_message']['error'] = 'В доступе отказано. Для продолжения авторизуйтесь снова.';
			}
			else
			{
				return $login_result;
			}
		}
		else
		{
			$login_result = false;
		}
	
		if ($login_result === false)
		{
			header("Location: /control/login/?ret=$ret");die();
		}
	}
	/**
	 * Users::verify_user_access()
	 * 
	 * @param mixed $login
	 * @param mixed $password
	 * @param integer $pass_in_md5
	 * @return
	 */
	function verify_user_access ($login, $password, $pass_in_md5 = 0)
	{
	    // Если пароль в открытой форме, шифруем.
		if ($pass_in_md5 == 0)
		{
			$password = md5($password);
		}
	
	    // Флаг о необходимости запомнить пользователя
	    $remember = 0;
	    if (isset($_POST['remember']) && $_POST['remember'] == '1')
	        $remember = 1;
	
		// Проверка существования метки login_u и логина пользователя login
		// наличие login_u говорит о том что пользователь авторизуется на сайте.
		if (isset($_SESSION['login_u']) && isset($_SESSION['login']))
		{
			// Если полученный login не совпадает с зарегистрированным в сессии, "убиваем" данные в сессии
			if ($login != $_SESSION['login'])
			{
	    		unset($_SESSION['user_id']);
	    		unset($_SESSION['login']);
	    		unset($_SESSION['login_u']);
	    		unset($_SESSION['password']);
	    		unset($_SESSION['user_group']);
	    		setcookie("passport", "", time(), "/", ".".MAIN_DOMAIN, 0);
			}
			// Если совпадают, проверяем наличие доступа у пользвателя
			else
			{
				$query = "SELECT id FROM $this->table WHERE
					login='".mysql_real_escape_string($login)."' AND
					password = '".mysql_real_escape_string($_SESSION['password'])."'  LIMIT 1";
	
				$sql = $this->db->query($query);
				// Если доступ разрешен, возвращаем true
				if ($this->db->nums($sql) > 0)
				{
					$row = $this->db->fetch($sql);
					$user_id = $row[0];
					$user = $this->user_get_data ($user_id);
	
					$_SESSION['login'] 		= $login;
	        		$_SESSION['password'] 	= $user['password'];
	        		$_SESSION['user_id'] 	= $user_id;
	        		$_SESSION['user_group'] = $user['group'];
	        		$_SESSION['login_u'] 	= md5(time());
	
					$ar['last_ip'] = $this->get_client_ip();
					$ar['last_visited_page'] = $_SERVER['HTTP_HOST'].(isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : "");
					$ar['last_visit'] = time();
					$this->db->update($this->table_info, $ar, " WHERE $this->pid = '$user_id' ");
	
					if (!isset($_COOKIE['passport']))
					{
	                    $now_time = time();
	                    $data['f'] = $user_id;
	            		$data['g'] = $login;
	            		$data['s'] = substr($now_time, 0, 5).$password.substr($now_time, 2, 7);
	            		$data['c'] = md5("yar".$login.":".$password."land");
	
	
	            		setcookie("passport", "", time(), "/", ".".MAIN_DOMAIN, 0);
	
	                    if ($remember == '1')
	            		{
	                        setcookie("passport", serialize($data), time()+31536000, "/", ".".MAIN_DOMAIN, 0);
	                    }
	
	                    setcookie("passport", serialize($data), time()+86400, "/", ".".MAIN_DOMAIN, 0);
	
	                }
	
					return true;
				}
				// Иначе возвращаем уничтожаем данные
				else
				{
					unset($_SESSION['user_id']);
					unset($_SESSION['login']);
					unset($_SESSION['login_u']);
					unset($_SESSION['password']);
					unset($_SESSION['user_group']);
					setcookie("passport", "", time(), "/", ".".MAIN_DOMAIN, 0);
				}
			}
		}
	
		// Если нет метки login_u или нет данных в сессии, проверяем данные
	
		$query = "SELECT id FROM $this->table WHERE
					login='".mysql_real_escape_string($login)."' AND
					password = '".$password."' LIMIT 1";
	
		$sql = $this->db->query($query, __FILE__, __LINE__);
		if ($this->db->nums($sql) > 0)
		{
			$row = $this->db->fetch($sql);
			$user_id = $row[0];
			$user = $this->user_get_data ($user_id);
			$_SESSION['login'] 		= $login;
			$_SESSION['password'] 	= $password;
			$_SESSION['user_id'] 	= $user_id;
			$_SESSION['user_group'] = $user['group'];
			$_SESSION['login_u'] 	= md5(time());
	
			$ar['last_ip'] = $this->get_client_ip();
			$ar['last_visited_page'] = $_SERVER['HTTP_HOST'].(isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : "");//$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
			$ar['last_visit'] = time();
			$this->db->update($this->table_info, $ar, " WHERE $this->pid = '$user_id' ", __FILE__, __LINE__);
	
			$now_time = time();
			$data['f'] = $user_id;
			$data['g'] = $login;
			$data['s'] = substr($now_time, 0, 5).$password.substr($now_time, 2, 7);
			$data['c'] = md5("yar".$login.":".$password."land");
	
	    		setcookie("passport", "", time(), "/", ".".MAIN_DOMAIN, 0);
	
	    		if ($remember == '1')
	    		{
	                setcookie("passport", serialize($data), time()+31536000, "/", ".".MAIN_DOMAIN, 0);
	            }
	            setcookie("passport", serialize($data), time()+86400, "/", ".".MAIN_DOMAIN, 0);
	
	
			return serialize($data);
		}
		else
		{
			return false;
		}
	}
	/**
	 * Users::user_authorization()
	 * 
	 * @param string $page
	 * @return
	 */
	function user_authorization ($page = '/')
	{
	    if (isset($_COOKIE['passport']))
	    {
	        $login_result = $this->check_user();
			if ($login_result === false)
			{
				$_SESSION['system_message']['error'] = 'В доступе отказано. Проверьте правильность введенных данных.';
				setcookie("passport", "", time(), "/", ".".MAIN_DOMAIN, 0);
			}
			else
			{
				return $login_result;
			}
	
	    }
	
		if (isset($_POST['auth_submit']))
		{
			$login_result = $this->verify_user_access($_POST['login'], $_POST['password']);
			if ($login_result === false)
			{
				$_SESSION['system_message']['error'] = 'В доступе отказано. Проверьте правильность введенных данных.';
			}
			else
			{
				return $login_result;
			}
		}
		elseif (isset($_SESSION['login_u']) && isset($_SESSION['login']))
		{
			$login_result = $this->verify_user_access($_SESSION['login'], $_SESSION['password'], 1);
			if ($login_result === false)
			{
				$_SESSION['system_message']['error'] = 'В доступе отказано. Для продолжения авторизуйтесь снова.';
			}
			else
			{
				return $login_result;
			}
		}
		else
		{
			$login_result = false;
		}
	
		if ($login_result === false)
		{
	
			header("Location: /login.html?ref=".urldecode($page));die();
		}
	}
	/**
	 * Users::get_user_id()
	 * 
	 * @param mixed $login
	 * @return
	 */
	function get_user_id ($login)
	{
	    $query = $this->db->select($this->table, "id", " WHERE login = ::0 ", array($login));
	
	    $res = $this->db->fetch($query);
	    if (!empty($res))
	    {
	        return $res['id'];
	    }
	    else
	    {
	        return '0';
	    }
	}
	/**
	 * Users::get_user_login()
	 * 
	 * @param mixed $id
	 * @return
	 */
	function get_user_login ($id)
	{
	    $query = $this->db->select($this->table, "login", " WHERE id = ::0 ", array($id));
	
	    $res = $this->db->fetch($query);
	    if (!empty($res))
	    {
	        return $res['login'];
	    }
	    else
	    {
	        return '0';
	    }
	}
	/**
	 * Users::user_get_data()
	 * 
	 * @param mixed $user_id
	 * @return
	 */
	function user_get_data ($user_id)
	{
	
		$query = "SELECT u.login, u.password, u.email, ui.*, year(ui.first_data) as birthyear, month(ui.first_data) as birthmonth, day(ui.first_data) as birthday, ug.id as group_id, ug.group, ug.group_title FROM $this->table as u, $this->table_groups as ug, $this->table_info as ui WHERE
			u.id = '$user_id' AND
			ug.id = u.group AND
			ui.user_id = u.id LIMIT 1";
	
		$row = $this->db->fetch_one($query);
		if (!empty($row))
		{
			$user['id'] = $row['user_id'];
			$user['login'] = $row['login'];
			$user['password'] = $row['password'];
			$user['name'] = $row['name'];
			$user['lname'] = $row['lname'];
			$user['fname'] = $row['fname'];
			$user['company_id'] = $row['company_id'];
			$user['email'] = $row['email'];
			$user['last_ip'] = $row['last_ip'];
			$user['last_visit'] = $row['last_visit'];
			if ($row['last_visit'] > time()-300)
			{
			  $user['online'] = str_replace("http://", "", $row['last_visited_page']);
			  $user['online'] = str_replace(MAIN_DOMAIN, "http://".MAIN_DOMAIN, $user['online']);
			}
			$user['last_visit_date'] = time_to_date($row['last_visit']);
			$user['last_visited_page'] = $row['last_visited_page'];
			$user['reg_time'] = $row['reg_time'];
			$user['group_id'] = $row['group_id'];
			$user['group'] = $row['group'];
			$user['group_title'] = $row['group_title'];
			$user['sex'] = $row['sex'];
			$user['first_data'] = $row['first_data'];
	
			$user['birthday'] = array(
	                            "year"=>$row['birthyear'],
	                            "month"=>$row['birthmonth'],
	                            "day"=>$row['birthday']
	                            );
	        $user['age'] = '';
			if ($user['first_data'] != '0000-00-00')
			{
	            $now_year = date("Y");
	            $now_month = date("m");
	            $now_day = date("d");
	
	            $tomm_day = date("d", time()+86400);
	            $tomm_month = date("m", time()+86400);
	
	            $age = $now_year-$user['birthday']['year'];
	            if ($now_month < $user['birthday']['month'])
	            {
	                $age = $age-1;
	            }
	            elseif ($now_month == $user['birthday']['month'])
	            {
	                if ($now_day < $user['birthday']['day'])
	                    $age = $age-1;
	                elseif ($now_day == $user['birthday']['day'])
	                {
	                    $user['today_birthday'] = '1';
	                }
	            }
	            if ($tomm_day == $user['birthday']['day']
	             && $tomm_month == $user['birthday']['month'])
	            {
	                $user['tomorrow_birthday'] = '1';
	            }
	            $user['age'] = $age;
	            $user['age_str'] = uni_word_end("", $age, array("лет","года","год"));
	
			}
	
			$user['karma'] = round($row['karma'],2);
			$user['marital'] = $row['marital'];
			$user['rating'] = $row['rating'];
			$user['subscribe'] = $row['subscribe'];
			$user['photo'] = $row['photo'];
			$user['avatar'] = $row['avatar'];
			$user['mood'] = $row['mood'];
			$online = '';
			if (isset($user['online'])) $online = $user['online'];
	        $user['print_login'] = $this->user_login($user['login'], $user['sex'], $user['group'], '1', $online,$user['id']);
	        $user['text_login'] = $this->user_login($user['login'], $user['sex'], $user['group'], '0',$online,$user['id']);
			return $user;
		}
		else
		{
			return false;
		}
	}
	/**
	 * Users::get_users_data()
	 * 
	 * @param mixed $users_id
	 * @param string $order
	 * @return
	 */
	function get_users_data ($users_id = array(), $order = 'u.id')
	{
	    $users = array();
	
	    if (!empty($users_id))
	    {
	        $id_list = implode(", ", $users_id);
	
	        if ($order != '')
	        {
	            $order = 'ORDER BY '.$order;
	        }
	        else
	        {
	            $order = 'ORDER BY FIELD (u.id, '.$id_list.')';
	        }
	
	        $us = $this->db->fetch_array("SELECT u.login, u.password, u.email, ui.*, year(ui.first_data) as birthyear, month(ui.first_data) as birthmonth, day(ui.first_data) as birthday, ug.id as group_id, ug.group, ug.group_title FROM $this->table as u, $this->table_groups as ug, $this->table_info as ui WHERE
			u.id IN ($id_list) AND
			ug.id = u.group AND
			ui.user_id = u.id ".$order);
	
			$i = 0;
			foreach ($us as $k=>$v)
			{
	            $users[$i] = array (
	            'id'          => $v['user_id'],
	            'login'       => $v['login'],
	    		'password'    => $v['password'],
	    		'name'        => $v['name'],
	    		'lname'       => $v['lname'],
	    		'fname'       => $v['fname'],
	    		'email'       => $v['email'],
	    		'last_ip'     => $v['last_ip'],
	    		'last_visit' => $v['last_visit'],
	    		'last_visit_date' => time_to_date($v['last_visit']),
	    		'last_visited_page' => $v['last_visited_page'],
	    		'reg_time' => $v['reg_time'],
	    		'group_id' => $v['group_id'],
	    		'group' => $v['group'],
	    		'group_title' => $v['group_title'],
	    		'sex' => $v['sex'],
	    		'first_data' => $v['first_data'],
	    		'birthday' => array(
	                                "year"=>$v['birthyear'],
	                                "month"=>$v['birthmonth'],
	                                "day"=>$v['birthday']
	                                ),
	    		'karma' => round($v['karma'],2),
	    		'rating' => $v['rating'],
	    		'subscribe' => $v['subscribe'],
	    		'photo' => $v['photo'],
	    		'avatar' => $v['avatar'],
	    		'mood' => $v['mood']
	    		);
	
	    		$online = '';
	    		if ($v['last_visit'] > time()-300)
	    		{
	    		  $users[$i]['online'] = str_replace("http://", "", $v['last_visited_page']);
	    		  $users[$i]['online'] = str_replace(MAIN_DOMAIN, "http://".MAIN_DOMAIN, $users[$i]['online']);
	    		  $online = $users[$i]['online'];
	    		}
	
	            $users[$i]['print_login'] = $this->user_login($v['login'], $v['sex'], $v['group'], 1,$online,$v['user_id']);
	            $users[$i]['text_login'] = $this->user_login($v['login'], $v['sex'], $v['group'], '0',$online,$v['user_id']);
	
	            $users[$i]['age'] = '';
	    		if ($users[$i]['first_data'] != '0000-00-00')
	    		{
	                $now_year = date("Y");
	                $now_month = date("m");
	                $now_day = date("d");
	
	                $tomm_day = date("d", time()+86400);
	                $tomm_month = date("m", time()+86400);
	
	                $age = $now_year-$users[$i]['birthday']['year'];
	                if ($now_month < $users[$i]['birthday']['month'])
	                {
	                    $age = $age-1;
	                }
	                elseif ($now_month == $users[$i]['birthday']['month'])
	                {
	                    if ($now_day < $users[$i]['birthday']['day'])
	                        $age = $age-1;
	                    elseif ($now_day == $users[$i]['birthday']['day'])
	                    {
	                        $users[$i]['today_birthday'] = '1';
	                    }
	                }
	                if ($tomm_day == $users[$i]['birthday']['day']
	                 && $tomm_month == $users[$i]['birthday']['month'])
	                {
	                    $users[$i]['tomorrow_birthday'] = '1';
	                }
	                $users[$i]['age'] = $age;
	                $users[$i]['age_str'] = uni_word_end("", $age, array("лет","года","год"));
	
	    		}
	
	
	            $i++;
			}
	    }
	    return $users;
	}
	/**
	 * Users::check_user()
	 * 
	 * @param string $ch
	 * @return
	 */
	function check_user($ch = '')
	{
	    $d = '';$t = '';
	
	    if (isset($_COOKIE['passport']))
	    {
	        $d = $_COOKIE['passport'];
	        $t = 'cookie';
	    }
	    elseif (isset($_SESSION['passport']))
	    {
	        $d = $_SESSION['passport'];
	        $t = 'session';
	    }
	    elseif($ch != '')
	    {
	        $d = $ch;
	        $t = 'str';
	    }
	
	    if ($d != '')
	    {
	        $data = unserialize($d);
	        $passport['login'] = $data['g'];
	        $passport['user_id'] = $data['f'];
	        $passport['check'] = $data['c'];
	
	        $p = $this->db->fetch_one("SELECT password FROM $this->table WHERE id = '".$passport['user_id']."'");
	        if (empty($p))
	        {
	            return false;
	        }
	        $check = md5("yar".$passport['login'].":".$p['password']."land");
	
	        if ($check !== $passport['check'])
	        {
				setcookie("passport", "", 0, "/", ".".MAIN_DOMAIN, 0);
	
	            unset($_SESSION['login']);
	            unset($_SESSION['password']);
	            unset($_SESSION['passport']);
	            unset($_SESSION['user_id']);
	            unset($_SESSION['user_group']);
	            unset($_SESSION['login_u']);
	            return false;
	        }
	        else
	        {
				$ar['last_ip'] = $this->get_client_ip();
	    		$ar['last_visited_page'] = $_SERVER['HTTP_HOST'].(isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : "");
	    		$ar['last_visit'] = time();
	    		$this->db->update($this->table_info, $ar, " WHERE $this->pid = '".$passport['user_id']."' ");
	
	            $user_data = $this->user_get_data($passport['user_id']);
	
	            $now_time = time();
	    		$data['f'] = $user_data['id'];
	    		$data['g'] = $user_data['login'];
	    		$data['s'] = substr($now_time, 0, 5).$user_data['password'].substr($now_time, 2, 7);
	    		$data['c'] = md5("yar".$user_data['login'].":".$user_data['password']."land");
	            $_SESSION['passport'] 	= serialize($data);
	            $_SESSION['login'] 		= $user_data['login'];
	    		$_SESSION['password'] 	= $user_data['password'];
	    		$_SESSION['user_id'] 	= $user_data['id'];
	    		$_SESSION['user_group'] = $user_data['group'];
	    		$_SESSION['login_u'] 	= md5(time());
	
	            setcookie("passport", serialize($data), time()+365*86400, "/", ".".MAIN_DOMAIN, 0);
	
	            return $user_data;
	        }
	    }
	
	    else
	    {
	        if (isset($_SESSION['login_u']))
	        {
	            unset($_SESSION['login']);
	            unset($_SESSION['password']);
	            unset($_SESSION['user_id']);
	            unset($_SESSION['user_group']);
	            unset($_SESSION['login_u']);
	            unset($_SESSION['passport']);
	        }
	        if (isset($_COOKIE['passport'])) setcookie("passport", "", 0, "/", ".".MAIN_DOMAIN, 0);
	        return false;
	    }
	}
	/**
	 * Users::user_login()
	 * 
	 * @param mixed $login
	 * @param mixed $sex
	 * @param string $group
	 * @param string $link
	 * @param string $online
	 * @param string $user_id
	 * @return
	 */
	function user_login ($login, $sex , $group = 'user', $link = '1', $online = '', $user_id = '0')
	{
	    $url = MAIN_URL."u/".$login."/";
	    $first_letter = substr($login, 0, 1);
	    $other = substr($login, 1, strlen($login));
	    //$user_id = get_user_id($login);
	
	    $online_flag = '<img src="'.I_URL.'/not_online.gif" alt="нет на сайте" border="0" title="нет на сайте" class="online_img" align="bottom" />';
	
	    if ($online != '')
	    {
	        $online_flag =  '<img src="'.I_URL.'/online.gif" alt="сейчас на сайте" border="0" title="сейчас на сайте" class="online_img" align="bottom"  />';
	    }
	
	
	    if ($sex == 'm')
	    {
	        $first_letter = '<span class="nickm">'.$first_letter.'</span>';
	    }
	    elseif ($sex == 'f')
	    {
	        $first_letter = '<span class="nickw">'.$first_letter.'</span>';
	    }
	    if ($group == 'user')
	    {
	        $other = '<span class="nick" title="'.($online != '' ? 'сейчас на сайте' : '').'">'.$other.'</span>';
	    }
	    if ($group == 'admin')
	    {
	        $other = '<span class="nick" title="Администратор. '.($online != '' ? 'сейчас на сайте' : '').'">'.$other.'</span>';
	    }
	    elseif ($group == 'moderator')
	    {
	        $other = '<span class="nick mnick"  title="Модератор сайта. '.($online != '' ? 'сейчас на сайте' : '').'">'.$other.'</span>';
	    }
	    elseif ($group == 'superadmin')
	    {
	        $other = '<span class="nick anick" title="Администратор сайта. '.($online != '' ? 'сейчас на сайте' : '').'">'.$other.'</span>';
	    }
	    $res = $online_flag.($link == '1' ? '<a href="'.$url.'" class="nick user_'.$user_id.'">' : '').$first_letter.$other.($link == '1' ? '</a>' : '');
	
	
	    return $res;
	
	}
	/**
	 * Users::encode_ip()
	 * 
	 * @param mixed $dotquad_ip
	 * @return
	 */
	function encode_ip($dotquad_ip)
	{
		$ip_sep = explode('.', $dotquad_ip);
		return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
	}
	/**
	 * Users::decode_ip()
	 * 
	 * @param mixed $int_ip
	 * @return
	 */
	function decode_ip($int_ip)
	{
		$hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
		return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
	}
	/**
	 * Users::create_notify()
	 * 
	 * @param mixed $obj_id
	 * @param mixed $user_id
	 * @param mixed $module
	 * @param mixed $message
	 * @param string $to
	 * @return
	 */
	function create_notify ($obj_id, $user_id, $module, $message, $to = 'all')
	{
	   /* global $this->db;
	
	    $available_modules = array("blog", "photo", "album", "friend", "club", "blog_comments", "photo_comments");
	
	    if (!in_array($module, $available_modules))
	    {
	        return false;
	    }
	
	    $friends_id = $this->db->fetch_list("SELECT user_id FROM ".$this->pfx."friends WHERE friend_id = '$user_id' AND status = '1' AND watch = '1'");
	
	    $addr_id = array();
	    if(!empty($friends_id))
	    {
	        $addr_id = $friends_id;
	    }
	
	    if ($to == 'all')
	    {
	        $subs_id = $this->db->fetch_list("SELECT user_id FROM $this->pfx."."subscribers WHERE owner_id = '$user_id' AND module = '$module' AND obj_id = '$obj_id'");
	        if(!empty($subs_id))
	        {
	            $addr_id = array_merge($addr_id, $subs_id);
	        }
	    }
	
	    if(empty($addr_id))
	    {
	        return false;
	    }
	
	    $up = array (
	        "obj_id" => $obj_id,
	        "module" => $module,
	        "status" => '1',
	        "owner_id" => $user_id,
	        "time" => time(),
	        "message" => $message
	    );
	    // Отправка уведомлений
	    $counter = 0;
	    foreach ($addr_id as $k=>$uid)
	    {
	        $up['user_id'] = $uid;
	        $this->db->insert($this->pfx."events", $up);
	        $counter++;
	    }
	    return $counter;*/
	}
	/**
	 * Users::remove_notify()
	 * 
	 * @param mixed $obj_id
	 * @param mixed $user_id
	 * @param mixed $module
	 * @return
	 */
	function remove_notify ($obj_id, $user_id, $module)
	{
	
	}
	/**
	 * Users::read_notify()
	 * 
	 * @param mixed $obj_id
	 * @param mixed $user_id
	 * @param mixed $module
	 * @return
	 */
	function read_notify ($obj_id, $user_id, $module)
	{
	
	}
	
	/**
	 * Users::create_event()
	 * 
	 * @param mixed $user_id
	 * @param mixed $meta
	 * @return
	 */
	function create_event($user_id, $meta = array())
	{
	    //$modules = array("photo_comment", "blog_comment", "club_blog_comment");
	
	    $module = $meta['module'];
	    $obj_id = $meta['obj_id'];
	    $object = $meta['object']; // comment OR other
	    $author = $this->user_get_data($user_id);
	
	    if ($object == 'comment')
	    {
	        $type   = $meta['type'];  // new OR answer
	
	        $comment_id = $meta['handler_id'];
	
	        if ($type == 'answer')
	        {
	            $action_title = 'ответил'.($author['sex'] == 'f' ? 'а':'').'  на ваш ';
	        }
	        elseif ($type == 'new')
	        {
	
	            $action_title = 'написал'.($author['sex'] == 'f' ? 'а':'');
	        }
	
	        switch ($module)
	        {
	            case "users_photos":
	                $ins_module = 'photo_comment';
	                $photo = $this->db->fetch_one("SELECT * FROM $this->table_photos WHERE id = '$obj_id'");
	                $owner_login = $this->get_user_login($photo['user_id']);
	                $owner_id = $photo['user_id'];
	                $link = '/u/'.$owner_login.'/photo/album_'.$photo['album_id'].'/'.$photo['id'].'/';
	
	                $message = $author['print_login'].' '.$action_title.' комментарий к фотографии <a href="'.$link.'">&laquo;'.($photo['title'] != '' ? $photo['title'] : 'без названия').'&raquo;</a><br /><br /><a href="'.$link.'?show_comments=1#comment_'.$comment_id.'">Перейти к комментарию</a>';
	
	            break;
	            case "users_blogs":
	                $ins_module = 'blog_comment';
	                $post = $this->db->fetch_one("SELECT * FROM $this->table_blogs WHERE id = '".$obj_id."'");
	                $owner_login = $this->get_user_login($post['user_id']);
	                $owner_id = $post['user_id'];
	                $link = '/u/'.$owner_login.'/blog/post_'.$post['id'].'/';
	                $message = $author['print_login'].' '.$action_title.' комментарий к посту <a href="'.$link.'">&laquo;'.($post['title'] != '' ? $post['title'] : 'без названия').'&raquo;</a><br /><br /><a href="'.$link.'?show_comments=1#comment_'.$comment_id.'">Перейти к комментарию</a>';
	
	            break;
	            case "users_clubs_blogs":
	                $ins_module = 'club_blog_comment';
	                $post = $this->db->fetch_one("SELECT * FROM ".$this->pfx."clubs_blogs WHERE id = '".$obj_id."'");
	                if ($type == 'new')
	                {
	                    $owner_id = $this->db->fetch_list("SELECT user_id FROM ".$this->pfx."clubs_members WHERE club_id = '".$post['club_id']."' AND status = '2'");
	                }
	
	                $club = $this->db->fetch_one("SELECT * FROM $this->table_clubs WHERE id = '".$post['club_id']."'");
	                $link = '/u/club/'.$club['id'].'/blog/post_'.$post['id'].'/';
	                $message = $author['print_login'].' '.$action_title.' комментарий к посту <a href="'.$link.'">&laquo;'.($post['title'] != '' ? $post['title'] : 'без названия').'&raquo;</a> в клубе <a href="/u/club/'.$club['id'].'/">&laquo;'.($club['title'] != '' ? $club['title'] : 'без названия').'&raquo;</a><br /><br /><a href="'.$link.'?show_comments=1#comment_'.$comment_id.'">Перейти к комментарию</a>';
	
	            break;
	        }
	
	        if (isset($meta['owner_id']))
	        {
	            $owner_id = $meta['owner_id'];
	        }
	
	        if (is_array($owner_id))
	        {
	            foreach ($owner_id AS $k=>$oid)
	            {
	                if ($user_id != $oid && !isset($meta['me_send']))
	                {
	                    $ins = array (
	                        "user_id" => $user_id,
	                        "owner_id" => $oid,
	                        "obj_id" => $obj_id,
	                        "message" => $message,
	                        "module" => $ins_module,
	                        "time" => time(),
	                        "status" => '0'
	                    );
	                    $this->db->insert($this->table_events,$ins);
	                }
	            }
	        }
	        elseif ($user_id != $owner_id)
	        {
	            if (!isset($meta['me_send']))
	            {
	                $ins = array (
	                    "user_id" => $user_id,
	                    "owner_id" => $owner_id,
	                    "obj_id" => $obj_id,
	                    "message" => $message,
	                    "module" => $ins_module,
	                    "time" => time(),
	                    "status" => '0'
	                );
	                $this->db->insert($this->table_events,$ins);
	            }
	        }
	        return true;
	    }
	}
	
	// Рейтинг
	//Снять рейтинг
	/**
	 * Users::take_user_rating()
	 * 
	 * @param mixed $user_id
	 * @param mixed $summ
	 * @param mixed $reason
	 * @return
	 */
	function take_user_rating ($user_id, $summ, $reason)
	{
	    $now_rating = $this->get_user_rating($user_id);
	    $ins = array (
	        'user_id' => $user_id,
	        'summa'   => $summ,
	        'reason'  => $reason,
	        'time'    => time()
	    );
	    $this->db->insert($this->table_ratings, $ins);
	    $new_rating = $now_rating + $summ;
	    $this->db->query("UPDATE $this->table_info SET rating = '$new_rating' WHERE $this->pid = '$user_id' ");
	    return $new_rating;
	}
	/**
	 * Users::get_user_rating()
	 * 
	 * @param mixed $user_id
	 * @return
	 */
	function get_user_rating ($user_id)
	{
	    $res = $this->db->fetch_one("SELECT rating FROM $this->table_info WHERE $this->pid = '$user_id'");
	    if (!empty($res))
	    {
	        return $res[0];
	    }
	    return false;
	}
	
	// Карма
	// Изменение
	/**
	 * Users::karmaChange()
	 * 
	 * @param mixed $obj_id
	 * @param mixed $owner_id
	 * @param mixed $owner_type
	 * @param mixed $module
	 * @param integer $karma
	 * @return
	 */
	function karmaChange ($obj_id, $owner_id, $owner_type, $module, $karma = 1)
	{
	    $ins = array
	    (
	        'user_id' => $_SESSION['user_id'],
	        'obj_id'   => $obj_id,
	        'owner_id' => $owner_id,
	        'owner_type' => $owner_type,
	        'karma'  => ($karma == '1' ? '1' : '-1'),
	        'module' => $module,
	        'time'    => time()
	    );
	    $this->db->insert($this->table_karma, $ins);
	
	    $obj_karma = $this->karmaObj($obj_id, $owner_id, $owner_type, $module);
	    $owner_karma = $this->karmaSum($owner_id, $owner_type);
	
	    switch ($owner_type)
	    {
	        case "club":
	            $this->db->query("UPDATE $this->table_clubs SET karma = '$owner_karma' WHERE id = '$owner_id' ");
	
	            if ($module == 'post')
	            {
	                $this->db->query("UPDATE ".$this->pfx."clubs_blogs SET karma = '$obj_karma' WHERE id = '$obj_id' ");
	
	                $author = $this->db->fetch_one("SELECT user_id FROM ".$this->pfx."clubs_blogs WHERE club_id = '$owner_id' AND id = '$obj_id'");
	                if ($author)
	                {
	                    $this->karmaChange ($obj_id, $author[0], 'user', $module, $karma);
	                }
	            }
	        break;
	        case "user":
	            if ($module == 'post')
	            {
	                $this->db->query("UPDATE $this->table_blogs SET karma = '$obj_karma' WHERE id = '$obj_id' ");
	            }
	            elseif ($module == 'comment')
	            {
	                $this->db->query("UPDATE ".$this->db->pfx."comments SET karma = '$obj_karma' WHERE id = '$obj_id' ");
	            }
	            $this->db->query("UPDATE $this->table_info SET karma = '$owner_karma' WHERE $this->pid = '$owner_id' ");
	        break;
	    }
	    return $obj_karma;
	}
	/**
	 * Users::karmaSum()
	 * 
	 * @param mixed $owner_id
	 * @param mixed $owner_type
	 * @return
	 */
	function karmaSum($owner_id, $owner_type)
	{
	    $karma = 0;
	    $res_posts = $this->db->fetch_one("SELECT SUM(karma) FROM $this->table_karma WHERE owner_id = '$owner_id' AND owner_type = '$owner_type' AND module = 'post' ");
	    if ($res_posts[0] != '')
	    {
	        $karma = $karma + $res_posts[0];
	    }
	
	    $res_comments = $this->db->fetch_one("SELECT SUM(karma*0.1) FROM $this->table_karma WHERE owner_id = '$owner_id' AND owner_type = '$owner_type' AND module = 'comment' ");
	    if ($res_comments[0] != '')
	    {
	        $karma = $karma + $res_comments[0];
	    }
	
	     $res_owner = $this->db->fetch_one("SELECT SUM(karma) FROM $this->table_karma WHERE owner_id = '$owner_id' AND owner_type = '$owner_type' AND module = '$owner_type' ");
	    if ($res_owner[0] != '')
	    {
	        $karma = $karma + $res_owner[0];
	    }
	    return $karma;
	}
	/**
	 * Users::karmaObj()
	 * 
	 * @param mixed $obj_id
	 * @param mixed $owner_id
	 * @param mixed $owner_type
	 * @param mixed $module
	 * @return
	 */
	function karmaObj($obj_id, $owner_id, $owner_type, $module)
	{
	    $res = $this->db->fetch_one("SELECT SUM(karma) FROM $this->table_karma WHERE owner_id = '$owner_id' AND obj_id = '$obj_id' AND module = '$module' AND owner_type = '$owner_type' ");
	    if ($res[0] != '')
	    {
	        return $res[0];
	    }
	    return '0';
	}
	/**
	 * Users::karmaVoteUser()
	 * 
	 * @param mixed $obj_id
	 * @param mixed $owner_id
	 * @param mixed $owner_type
	 * @param mixed $module
	 * @param mixed $user_id
	 * @return
	 */
	function karmaVoteUser($obj_id, $owner_id, $owner_type, $module, $user_id)
	{
	    $res = $this->db->fetch_one("SELECT COUNT(*) FROM $this->table_karma WHERE owner_id = '$owner_id' AND obj_id = '$obj_id' AND module = '$module' AND owner_type = '$owner_type' AND user_id = '$user_id' ");
	
	    if ($res[0] != '0')
	    {
	        return $res[0];
	    }
	    return '';
	}
	/**
	 * Users::get_last_chat_wins()
	 * 
	 * @param mixed $visitor_data
	 * @return
	 */
	function get_last_chat_wins ($visitor_data)
	{
	    $my_chat = array();$chats_with = array();
	    if (isset($_COOKIE['last_chat_wins']))
	    {
	        $wins = explode(";", $_COOKIE['last_chat_wins']);
	
	        if (!empty($wins))
	        {
	            $i = 0;
	            foreach ($wins as $k=>$v)
	            {
	                if ($v != '')
	                {
	                    $from_user = $this->user_get_data($v);
	                    if(!empty($from_user))
	                    {
	                        $chats_with[] = $from_user['id'];
	                        $msgs = $this->db->fetch_array("SELECT * FROM $this->table_messages WHERE ((author_id = '".$_SESSION['user_id']."' AND recip_id = '$v') OR (author_id = '$v' AND recip_id = '".$_SESSION['user_id']."')) AND $this->pid = '".$_SESSION['user_id']."' ORDER BY time DESC LIMIT 10");
	                        if (!empty($msgs))
	                        {
	                            $msgs  = array_reverse($msgs);
	                            foreach ($msgs as $kk=>$vv)
	                            {
	                                $msgs[$kk]['date'] = date("H:i, d.m.Y", $vv['time']);
	
	                                $msgs[$kk]['author'] = ($vv['author_id']==$_SESSION['user_id'] ? $visitor_data['text_login'] : $from_user['text_login']);
	                                if ($vv['status'] == '0')
	                                {
	                                    $my_chat[$i]['unread'] = '1';
	                                    //$this->db->query("UPDATE ".PFX."users_msgs SET status = '1' WHERE id = '".$vv['id']."' AND user_id = '".$_SESSION['user_id']."'");
	                                }
	                            }
	                        }
	                        $my_chat[$i]['msgs'] = $msgs;
	                        $my_chat[$i]['from'] = $from_user;
	                        $i++;
	
	                        $_SESSION['last_check_chat'] = time();
	                    }
	                }
	            }
	        }
	    }
	
	    $q = '';
	    if (!empty($chats_with))
	    {
	        $q = "AND author_id NOT IN ('".implode("', '",$chats_with)."') ";
	    }
	
	    if (!isset($i)) $i = 0;
	    $authors = $this->db->fetch_array("SELECT author_id FROM $this->table_messages WHERE recip_id = '".$_SESSION['user_id']."' AND $this->pid = '".$_SESSION['user_id']."' $q AND status = '0' GROUP BY author_id ORDER BY time DESC");
	    if (!empty($authors))
	    {
	        foreach ($authors as $k=>$v)
	        {
	            $from_user = $this->user_get_data ($v['author_id']);
	            if(!empty($from_user))
	            {
	                $msgs = $this->db->fetch_array("SELECT * FROM $this->table_messages WHERE ((author_id = '".$_SESSION['user_id']."' AND recip_id = '".$v['author_id']."') OR (author_id = '".$v['author_id']."' AND recip_id = '".$_SESSION['user_id']."')) AND $this->pid = '".$_SESSION['user_id']."' ORDER BY time DESC LIMIT 10");
	                if (!empty($msgs))
	                {
	                    $msgs  = array_reverse($msgs);
	                    foreach ($msgs as $kk=>$vv)
	                    {
	                        $msgs[$kk]['date'] = date("H:i, d.m.Y", $vv['time']);
	
	                        $msgs[$kk]['author'] = ($vv['author_id']==$_SESSION['user_id'] ? $visitor_data['text_login'] : $from_user['text_login']);
	                        if ($vv['status'] == '0')
	                        {
	                            $my_chat[$i]['unread'] = '1';
	                            //$this->db->query("UPDATE ".PFX."users_msgs SET status = '1' WHERE id = '".$vv['id']."' AND user_id = '".$_SESSION['user_id']."'");
	                        }
	                    }
	                }
	                $my_chat[$i]['msgs'] = $msgs;
	                $my_chat[$i]['from'] = $from_user;
	                $i++;
	
	                $_SESSION['last_check_chat'] = time();
	            }
	        }
	    }
	
	    return $my_chat;
	}
	function create_admin_menu($active_module = '')
	{
	    global $db,$db_main, $user;
	    
		// Получение имен установленных модулей
		$var = $db->fetch_array("SELECT name, sort FROM ".PFX."control_modules WHERE status = '1' GROUP BY name");
	
		if (empty($var))
		{
			return false;
		}
	
		$main_menu = array();
		
		foreach($var as $k => $mod)
		{
			if(file_exists(A_MOD_DIR.$mod['name'].'/info'.MOD_EXT))
			{
				require (A_MOD_DIR.$mod['name'].'/info'.MOD_EXT);
				
				   $access = $this->check_access($user['id'], $user['group_id'], $mod['name']);
				    if ($access == 'none')
				         $module['deny'] = 1;
					$main_menu[$mod['sort']] = $module;
			}
			
		}
	
	
		ksort ($main_menu);
		
		$sub_menu = array();
		foreach ($main_menu as $k => $mm)
		{
			if ($mm['name'] == $active_module)
			{
				$main_menu[$k]['selected'] = '1';
	
				if (!empty($mm['menu']))
				{
					foreach ($mm['menu'] as $j => $smenu)
					{
						$sub_menu[] = $smenu;
					}
				}
			}
		}
	
		return array("menu" => $main_menu, "submenu" => $sub_menu);
	}
	
	function check_access($user_id, $group, $module)
	{
	    global $db;
	
	    $access = 'none';
	    
	    $group_access = $db->fetch_one("SELECT access FROM ".PFX."users_group_access WHERE group_id = '$group' AND module = '$module' LIMIT 1");
	    
	    if (!empty($group_access))
	    {
	        $access = $group_access['0'];
	    }
	   
	    $user_access = $db->fetch_one("SELECT access FROM ".PFX."users_access WHERE user_id = '$user_id' AND module = '$module' LIMIT 1");
	    
	    if (!empty($user_access))
	    {
	        $access = $user_access['0'];
	    }
	    
	    return $access;
	}
}


?>